package itemsaver

import (
	"context"
	"learn/crawler/engine"
	"log"

	"github.com/pkg/errors"
	"gopkg.in/olivere/elastic.v5"
)

func ItemSaver() (chan engine.Item, error) {
	out := make(chan engine.Item)

	client, err := elastic.NewClient(elastic.SetSniff(false))
	if err != nil {
		panic(err)
	}
	go func() {
		itemCount := 0
		for {
			item := <-out
			log.Printf("got item#%d, %+v", itemCount, item)
			itemCount++
			err := save(client, item)

			if err != nil {
				log.Printf("saving item error: %v", err)
			}
		}
	}()

	return out, nil
}

//save item
func save(client *elastic.Client, item engine.Item) (err error) {
	if item.Type == "" {
		return errors.New("must supply type")
	}

	indexService := client.Index().Index("zhaopin").
		Type(item.Type)

	if item.Id != "" {
		indexService.Id(item.Id)
	}

	_, err = indexService.BodyJson(item).Do(context.Background())

	if err != nil {
		return err
	}

	return nil
}
